var selectedMenuid = -1;
var selectedMenu = [], notSelectedMenu = [];
/**
 * 切换角色触发菜单事件
 */
function changeRoleMenu() {
    selectedMenu = [];
    notSelectedMenu = [];
    $("#m_tabs_2_1 .select-group").empty();
    getSelectedMenu();
    $("#menutree-div").empty();
    laytpl($("#tree-template").html()).render({}, function (html) {
        $("#menutree-div").append(html);
    });
    $("#tree").jstree("destroy");
    initMenuTree($("#tree"));
    initMenuEvent();
}

/**
 * 初始化通讯录树
 */
function initMenuTree(_this) {
    _this.jstree({
        core: {
            themes: {
                responsive: !1
            },
            data: function(node, callback) {
                loadMenuData(node, callback);
            }
        },
        types: {
            default: {
                icon: "la la-align-left m--font-brand"
            }
        },
        state: {
            key: "contact_tree"
        },
        plugins: ["checkbox", "types"]
    }).on("select_node.jstree", function (node, selected) {
        appendSelectedItem(selected.node, _this);
        appendChildren(selected.node, _this);
        appendParent(selected.node, _this);
    }).on("deselect_node.jstree", function (node, selected) {
        $(".select-" + selected.node.id).remove();
        arrayDeleteItem(selectedMenu, selected.node.id);
        removeChildren(selected.node, _this);
        removeParent(selected.node, _this);
    }).on("ready.jstree", function (event, data) {
        for (var i = 0; i < selectedMenu.length; i++) {
            _this.jstree('select_node', selectedMenu[i], true);
        }
        for (var j = 0; j < notSelectedMenu.length; j++) {
            _this.jstree('deselect_node', notSelectedMenu[j]);
        }
    });
}

/**
 * 追加子菜单
 * @param node
 * @param _this
 */
function appendChildren(node, _this) {
    var children = node.children;
    if (children.length > 0) {
        for (var i = 0; i < children.length; i++) {
            var temp_node = _this.jstree("get_node", children[i]);
            appendSelectedItem(temp_node, _this);
            appendChildren(temp_node, _this);
        }
    }
}

/**
 * 移除子菜单
 * @param node
 * @param _this
 */
function removeChildren(node, _this) {
    var children = node.children;
    if (children.length > 0) {
        for (var i = 0; i < children.length; i++) {
            $(".select-" + children[i]).remove();
            arrayDeleteItem(selectedMenu, children[i]);
            var temp_node = _this.jstree("get_node", children[i]);
            removeChildren(temp_node, _this);
        }
    }
}

/**
 * 追加父菜单
 * @param node
 * @param _this
 */
function appendParent(node, _this) {
    var parentid = node.parents[0];
    if (!isNaN(parentid) && parentid != 0) {
        var parent_node = _this.jstree("get_node", parentid);
        appendSelectedItem(parent_node, _this);
    }
}

/**
 * 移除父菜单
 * @param node
 */
function removeParent(node, _this) {
    var parentid = node.parents[0];
    if (!isNaN(parentid) && parentid != 0) {
        var parent_node = _this.jstree("get_node", parentid);
        var children = parent_node.children;
        var flag = true;
        for (var i = 0; i < children.length; i++) {
            if ($.inArray(children[i], selectedMenu) >= 0){
                flag = false;
                break;
            }
        }
        if (flag) {
            $(".select-" + parentid).remove();
        }
    }
}

/**
 * 加载菜单数据
 * @param node
 * @param callback
 */
function loadMenuData(node, callback) {
    var fatherid = 0;
    if (node.id != "#") {
        fatherid = node.original.id;
    }
    $.hcPostAjax({
        msgPrefix: '加载菜单数据出错：',
        url: basePath + '/menu/list',
        data: {
            fatherid: fatherid
        },
        success: function (data) {
            var treeData = [];
            if (data !== undefined || data !== null) {
                var allSelected = true;
                $(data).each(function () {
                    treeData.push(buildMenuNode(this));
                    if ($.inArray(this.id.toString(), selectedMenu) < 0) {
                        allSelected = false;
                    }
                });

                if (!allSelected) {
                    deSelectParentNode(node);
                }
            }
            callback.call(this, treeData);
        }
    });
}

function deSelectParentNode(node) {
    if (node.id != '#' && node.state && node.state.selected) {
        $("#menutree-div").jstree("deselect_node", node.id);
        var arr = node.parents;
        for (var i = 0; i < arr.length; i++) {
            deSelectParentNode($("#menutree-div").jstree("get_node", arr[i]));
        }
    }
}

/**
 * 组装菜单节点
 * @param obj
 * @returns {{text: *, id: *, state: {opened: boolean, selected: boolean, disabled: boolean}, children: boolean}}
 */
function buildMenuNode(obj) {
    if ($.inArray(obj.id.toString(), selectedMenu) < 0) {
        notSelectedMenu.push(obj.id.toString());
    }
    return {
        text: obj.url === '' ? obj.name : obj.name + '(' + obj.url + ')',
        id: obj.id,
        state: {
            'opened': false,  //表示是否立即打开
            'selected': false, //是否选中，这边可以支持表达式，函数等
            "disabled": false //是否禁用，这边可以支持表达式，函数等
        },
        children: true   //表示是否还有子节点
    };
}

/**
 * 渲染选中的元素
 * @param node
 */
function appendSelectedItem(node) {
    if (node.original.id !== 0) {
        if ($.inArray(node.original.id.toString(), selectedMenu) === -1) {
            selectedMenu.push(node.original.id.toString());
            var data = {
                iconClazz: node.icon,
                title: node.text,
                id: node.id
            };
            laytpl($("#data-select-li").html()).render(data, function (html) {
                $("#m_tabs_2_1 .select-group").append(html);
            });
        }
    }
}

/**
 * 绑定菜单事件
 */
function initMenuEvent() {

    /**
     * 移除选择的菜单
     */
    $("#m_tabs_2_1 .select-group").on("click", ".delete-btn", function () {
        $(this).parent().remove();
        $("#tree").jstree('uncheck_node', $(this).data("id"));
    });
}

/**
 * 保存角色菜单
 * @param roleid
 */
function saveRoleMenu() {
    $.hcPostAjax({
        msgPrefix: '保存角色菜单数据失败：',
        url: basePath + '/role/menu/save/batch',
        data: {
            menuids: selectedMenu.join(','),
            roleid: roleTree.jstree("get_selected")[0]
        },
        success: function () {
            layer.msg('保存成功！', {icon: 1,time:1500});
        }
    });
}

/**
 * 解除全部绑定
 */
function deleteRoleMenuAll() {
    var selected = roleTree.jstree("get_selected");
    var obj = roleTree.jstree("get_node", selected[0]);
    layer.confirm('确定解除<font color="red">[' + obj.text + ']</font>下的全部绑定菜单？', {
        icon: 3,
        title: '提示',
        btn: ['确定','取消'] //按钮
    }, function(index){
        $.hcPostAjax({
            showLoad: true,
            msgPrefix: '解除角色菜单绑定出错：',
            url: basePath + '/role/menu/delete/all',
            data: {roleid: obj.id},
            success: function (data) {
                layer.msg('解除角色菜单绑定成功！', {icon: 1,time:1500}, function () {
                    changeRoleMenu();
                });
            }
        })
    }, function(index){
        layer.close(index);
    });
}

/**
 * 获取已绑定的菜单
 */
function getSelectedMenu() {
    $.hcPostAjax({
        msgPrefix: '获取角色菜单数据失败：',
        url: basePath + '/menu/getByRole',
        data: {
            roleid: roleTree.jstree("get_selected")[0]
        },
        async: false,
        success: function (data) {
            if (data != null && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    selectedMenu.push(data[i].id.toString());
                    var node = {
                        title: (data[i].url != '' ? (data[i].name + "(" + data[i].url + ")") : data[i].name),
                        id: data[i].id,
                        type: 'tree' + data[i].systemid
                    };
                    laytpl($("#select-li").html()).render(node, function (html) {
                        $("#m_tabs_2_1 .select-group").append(html);
                    });
                }
            }
        }
    })
}